package 爆刷leetcode.day0614;

import java.util.HashSet;

/**
 * @Author yaya
 * @Create 2024/6/14 20:43
 * Description:
 */
public class Code0141_HasCycle {

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public boolean hasCycleBySet(ListNode head) {
        HashSet<ListNode> set = new HashSet<>();
        ListNode temp = head;
        while (temp != null) {
            if (set.contains(temp)) break;
            set.add(temp);
            temp = temp.next;
        }
        return temp == null ? false : true;
    }

    /**
     * 不使用set 100%！
     * @param head
     * @return
     */
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null){
            return false;
        }
        ListNode low = head.next;
        ListNode fast = head.next.next;
        while (fast != null && fast.next != null){
            low = low.next;
            fast = fast.next.next;
            if (low == fast){
                return true;
            }
        }

        return false;
    }
}
